package org.springframework.amqp.helloworld.async;


import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;

/**
 * @author zss
 * @date 2018-07-13 下午4:04
 * @describe:消息生产者
 */
@Configuration
public class ProducerConfiguration {

    protected final String helloWorldQueueName = "hello.world.async.queue";

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        //设置路由key，把消息队列作为路由key
        template.setRoutingKey(this.helloWorldQueueName);
        //使用系统默认的交换机
        return template;
    }

    @Bean
    public ConnectionFactory connectionFactory() {
        //创建消息队列工厂
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost", 5672);
        connectionFactory.setUsername("zss");
        connectionFactory.setPassword("zss");
        //使用自定义虚拟机
        connectionFactory.setVirtualHost("/zss");
        return connectionFactory;
    }

    @Bean
    public ScheduledProducer scheduledProducer() {
        return new ScheduledProducer();
    }

    @Bean
    public BeanPostProcessor postProcessor() {
        return new ScheduledAnnotationBeanPostProcessor();
    }


    /**
     * @Author: zss
     * @Date: 2018/7/13 下午4:30
     * @Description: 创建一个生产者任务调度每个5秒来发送一个消息
     */
    static class ScheduledProducer {

        @Autowired
        private volatile RabbitTemplate rabbitTemplate;

        private final AtomicInteger counter = new AtomicInteger();

        @Scheduled(fixedRate = 5000)
        public void sendMessage() {
            rabbitTemplate.convertAndSend("Hello World " + counter.incrementAndGet());
        }
    }

}

